<template>
  <CommonPage show-footer title="科普文章">
    <template #action>
      <div>
        <n-button type="primary" secondary @click="$table?.handleExport()">
          <TheIcon icon="mdi:download" :size="18" class="mr-5" />
          导出
        </n-button>
        <n-button type="primary" class="ml-16" @click="handleAdd">
          <TheIcon icon="material-symbols:add" :size="18" class="mr-5" />
          新建科普文章
        </n-button>
      </div>
    </template>

    <CrudTable
      ref="$table"
      v-model:query-items="queryItems"
      :extra-params="extraParams"
      :scroll-x="1200"
      :columns="columns"
      :get-data="api.getArticles"
      @on-checked="onChecked"
      @on-data-change="(data) => (tableData = data)"
    >
      <template #queryBar>
        <QueryBarItem label="标题" :label-width="65">
          <n-input
            v-model:value="queryItems.query"
            type="text"
            placeholder="请输入标题"
            @keypress.enter="$table?.handleSearch"
          />
        </QueryBarItem>
        <QueryBarItem label="所属科室" :label-width="65">
          <n-tree-select
            v-model:value="queryItems.dept"
            :options="departments"
            label-field="dept_name"
            key-field="id"
            children-field="children"
          />
        </QueryBarItem>
      </template>
    </CrudTable>
    <!-- 新增/编辑/查看 -->
    <CrudModal
      v-model:visible="modalVisible"
      :title="modalTitle"
      :loading="modalLoading"
      :show-footer="modalAction !== 'view'"
      @on-save="handleSave"
    >
      <n-form
        ref="modalFormRef"
        label-placement="left"
        label-align="left"
        :label-width="80"
        :model="modalForm"
        :disabled="modalAction === 'view'"
      >
        <n-form-item
          label="标题"
          path="title"
          :rule="{
            required: true,
            message: '请输入标题',
            trigger: ['input', 'blur'],
          }"
        >
          <n-input v-model:value="modalForm.title" placeholder="请输入标题" />
        </n-form-item>
        <n-form-item label="封面" path="icon">
          <n-upload
            ref="uploadRef"
            list-type="image-card"
            action=""
            :custom-request="Upload"
            :max="1"
          >
            <img :src="modalForm.photo" style="width: 100%" />
          </n-upload>
        </n-form-item>
        <n-form-item
          label="所属科室"
          path="dept_name"
          :rule="{
            required: true,
            message: '请选择所属科室',
            trigger: ['input', 'blur'],
          }"
        >
          <n-select
            v-model:value="modalForm.dept_name"
            :options="options"
            @update:value="handleUpdateValue"
          ></n-select>
        </n-form-item>
        <n-form-item
          label="链接"
          path="url"
          :rule="{
            required: true,
            message: '请输入链接',
            trigger: ['input', 'blur'],
          }"
        >
          <n-input v-model:value="modalForm.url" placeholder="请输入链接" />
        </n-form-item>
        <n-form-item
          label="介绍"
          path="content"
          :rule="{
            required: true,
            message: '请输入介绍内容',
            trigger: ['input', 'blur'],
          }"
        >
          <n-input
            v-model:value="modalForm.content"
            placeholder="请输入介绍内容"
            type="textarea"
            :autosize="{
              minRows: 3,
              maxRows: 5,
            }"
          />
        </n-form-item>
      </n-form>
    </CrudModal>
  </CommonPage>
</template>

<script setup>
import { NButton, NSwitch } from 'naive-ui'
import { formatDateTime, renderIcon, isNullOrUndef, getToken } from '@/utils'
import { useCRUD } from '@/composables'
import api from './api'
import baseApi from '@/api'

defineOptions({ name: 'ArticlePage' })

const $table = ref(null)
/** 表格数据，触发搜索的时候会更新这个值 */
const tableData = ref([])
const options = ref([])
/** QueryBar筛选参数（可选） */
const queryItems = ref({
  dept: 0
})
/** 补充参数（可选） */
const extraParams = ref({})
const departments = ref([])

onActivated(async () => {
  $table.value?.handleSearch()
  const dep = await api.getDepartments()
  departments.value = dep.data
  const res = await api.getDepartments()
  for (let i = 0; i < res.data.length; i++) {
    for (let j = 0; j < res.data[i].children.length; j++) {
      options.value.push({
        label: res.data[i].children[j].dept_name,
        value: res.data[i].children[j].id,
      })
    }
  }
})

const columns = [
  { title: 'id', key: 'id', width: 15, ellipsis: { tooltip: true } },
  { title: '科普文章标题', key: 'title', width: 80, ellipsis: { tooltip: true } },
  { title: '所属部门', key: 'dept_name', width: 40, ellipsis: { tooltip: true } },
  { title: '链接', key: 'url', width: 80, ellipsis: { tooltip: true } },
  { title: '描述', key: 'content', width: 30 },
  {
    title: '操作',
    key: 'actions',
    width: 100,
    align: 'center',
    fixed: 'right',
    hideInExcel: true,
    render(row) {
      return [
        h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            secondary: true,
            onClick: () => handleView(row),
          },
          { default: () => '查看', icon: renderIcon('majesticons:eye-line', { size: 14 }) }
        ),
        h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            style: 'margin-left: 15px;',
            onClick: () => handleEdit(row),
          },
          { default: () => '编辑', icon: renderIcon('material-symbols:edit-outline', { size: 14 }) }
        ),

        h(
          NButton,
          {
            size: 'small',
            type: 'error',
            style: 'margin-left: 15px;',
            onClick: () => handleDelete(row.id),
          },
          {
            default: () => '删除',
            icon: renderIcon('material-symbols:delete-outline', { size: 14 }),
          }
        ),
      ]
    },
  },
]

// 选中事件
function onChecked(rowKeys) {
  if (rowKeys.length) $message.info(`选中${rowKeys.join(' ')}`)
}
function handleUpdateValue(string, SelectOption) {
  modalForm.value.dept_name = SelectOption.label
  modalForm.value.department_id = SelectOption.value
  console.log(modalForm)
}

const Upload = ({ file, data, headers, withCredentials, action, onFinish }) => {
  let formdata = new FormData() //formdata格式
  formdata.append('image', file.file)
  formdata.append('business', 'image')
  // 接口请求
  baseApi
    .uploadImage(formdata)
    .then((res) => {
      console.log(res)
      modalForm.value.photo = res.data.url
      // 注意清空，要不接口会重复调用
      onFinish()
    })
    .catch((err) => {
      console.log(err)
    })
}

const {
  modalVisible,
  modalAction,
  modalTitle,
  modalLoading,
  handleAdd,
  handleDelete,
  handleEdit,
  handleView,
  handleSave,
  modalForm,
  modalFormRef,
} = useCRUD({
  name: '科普文章',
  initForm: { author: '大脸怪' },
  doCreate: api.addPost,
  doDelete: api.deleteArticle,
  doUpdate: api.updateArticle,
  refresh: () => $table.value?.handleSearch(),
})
</script>
